package edu.csl.study.springboot.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Curator 四种重连策略
 *   1.RetryUntilElapsed(int maxElapsedTimeMs, int sleepMsBetweenRetries)
 *     以sleepMsBetweenRetries的间隔重连,直到超过maxElapsedTimeMs的时间设置
 *   2.RetryNTimes(int n, int sleepMsBetweenRetries)
 *     指定重连次数
 *   3.RetryOneTime(int sleepMsBetweenRetry)
 *     重连一次,简单粗暴
 *   4.ExponentialBackoffRetry
 *     ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries)
 *     ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries, int maxSleepMs)
 *     时间间隔 = baseSleepTimeMs * Math.max(1, random.nextInt(1 << (retryCount + 1)))
 */
@Configuration
public class CuratorConfig {

    @Value("${curator.retryCount}")
    private int retryCount;

    @Value("${curator.retryBaseSleepTimeMs}")
    private int retryBaseSleepTimeMs;

    @Value("${curator.connectString}")
    private String connectString;

    @Value("${curator.namespace}")
    private String namespace;


    @Bean
    public CuratorFramework curatorFramework(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(retryBaseSleepTimeMs, retryCount);
        CuratorFramework client = CuratorFrameworkFactory.newClient(connectString, retryPolicy);
        client.start();
        client.usingNamespace(namespace);
        return client;
    }

}
